package com.system.depart.service.impl;

import com.system.depart.bean.Depart;
import com.system.depart.repository.DepartRepository;
import com.system.depart.service.DepartService;
import com.system.depart.vo.DepartItemVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @className: DepartServiceImpl
 * @description: TODO 类描述
 * @author: Li Chuanwei
 * @date: 2023/11/12 15:40
 * @Company: Copyright [日期] by [作者或个人]
 **/

@Service
public class DepartServiceImpl implements DepartService {

    @Autowired
    private DepartRepository departRepository;
    @Override
    public boolean saveDepart(Depart depart) {
        Depart obj = departRepository.save(depart);
        if(obj != null){
            return true;
        }
        return false;
    }

    @Override
    public boolean removeDepartById(int id) {
        if (departRepository.existsById(id)) {
            departRepository.deleteById(id);
            return true;
        }
        return false;
    }

    @Override
    public boolean modifyDepart(Depart depart) {
        Depart obj = departRepository.save(depart);
        if(obj != null){
            return true;
        }
        return false;
    }

    @Override
    public Depart getDepartById(int id) {
        if (departRepository.existsById(id)) {
            return departRepository.getReferenceById(id);
        }
        return null;
    }

    @Override
    public List<Depart> listAllDeparts() {
        return departRepository.findAll();
    }

    @Override
    public List<Depart> listAllParentDeparts() {
        return departRepository.findAllByParentId(0);
    }

    @Override
    public List<Depart> listChildDeparts(Integer parentId) {
        return departRepository.findAllByParentId(parentId);
    }

    @Override
    public List<DepartItemVO> getDepartItemVO() {
        List<Depart> departList = departRepository.findAll();
        List<DepartItemVO> departItemVOList = new ArrayList<>();
        for (Depart depart : departList) {
            DepartItemVO departItemVO = new DepartItemVO();
            departItemVO.setLabel(depart.getDName());
            departItemVO.setValue(depart.getDepartId());  // 假设 Depart 类中有获取 ID 的方法
            departItemVOList.add(departItemVO);
        }
        return departItemVOList;
    }

    @Override
    public String getDepartName(Integer departId) {
        Depart depart = getDepartById(departId);
        return depart.getDName();
    }

    @Override
    public List<Depart> listAllChildDeparts(Integer parentId) {
        return departRepository.findAllByParentIdNot(0);
    }
}
